package pwr.zpi.twop;

import com.badlogic.gdx.graphics.Color;


public class GameOfLifeLayer extends Thread {
	private final int MAX_NEIGHTBOURS = 3;
	private final int MIN_NEIGHTBOURS = 2;
	
	private ModelProvider modelProvider;
	private RendererGL20 renderer;
	private int layer;
	
	public GameOfLifeLayer(int layer) {
		this.layer = layer;
	}
	
	@Override
	public void run() {
		super.run();
		
		while(true) {
			Color[][] points = modelProvider.getModelData()[layer];
			calculateLife(points);
			renderer.setPointList(modelProvider.getPoints());
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) { }
		}
	}

	private void calculateLife(Color[][] points) {
		for (int i = 0; i < points.length; i++) {
			for (int j = 0; j < points[i].length; j++) {
				Color color = points[i][j];
				
				if(color == null) {
					if(canBeRessurected(points, i, j)) {
						points[i][j] = modelProvider.incrementOrCreateColor(null);
					}
				} else {
					if(isUnderPopulatedOrOverCrowded(points, i, j)) {
						points[i][j] = null;
					}
				}
			}
		}
	}

	private boolean isUnderPopulatedOrOverCrowded(Color[][] points, int x, int y) {
		int neightbourCounter = countNeightbours(points, x, y);
		neightbourCounter--;
//		return (neightbourCounter < MIN_NEIGHTBOURS) || (neightbourCounter > MAX_NEIGHTBOURS);
		return false;
	}

	private boolean canBeRessurected(Color[][] points, int x, int y) {
		int neightbourCounter = countNeightbours(points, x, y);
		return neightbourCounter == 3;
	}
	
	private int countNeightbours(Color[][] points, int x, int y) {
		int neightbours = 0;
		
		for (int i = x-1; i <= x+1; i++) {
			for (int j = y-1; j <= y+1; j++) {
				if(i >= 0 && i < points.length &&
					j >= 0 && j < points[x].length) {
					
					if(points[i][j] != null) {
						neightbours++;
					}
				}
			}
		}
		
		return neightbours;
	}

	public void setModelProvider(ModelProvider modelProvider) {
		this.modelProvider = modelProvider;
	}
	
	public void setRenderer(RendererGL20 renderer) {
		this.renderer = renderer;
	}
}
